package com.gitee.dolt.database.util;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.gitee.dolt.core.base.entity.SuperEntity;
import com.gitee.dolt.core.base.entity.SuperRemoteDataEntity;
import com.gitee.dolt.core.util.SpringUtils;

import java.lang.reflect.Field;

/**
 * @author LYH
 */
public class MybatisUtils {
    /**
     * 根据 bean字段 反射出 数据库字段
     *
     * @param beanField
     * @param entityClass
     * @return
     */
    public static String getDbField(String beanField, Class<?> entityClass) {
        Field field = ReflectUtil.getField(entityClass, beanField);
        if (field == null) {
            return StrUtil.EMPTY;
        }
        TableField tf = field.getAnnotation(TableField.class);
        if (tf != null && StrUtil.isNotEmpty(tf.value())) {
            String str = tf.value();
            return str;
        }
        String name = field.getName();
        MybatisPlusProperties mybatisPlusProperties = SpringUtils.getBean(MybatisPlusProperties.class);
        boolean mapUnderscoreToCamelCase = mybatisPlusProperties.getConfiguration().isMapUnderscoreToCamelCase();
        if (mapUnderscoreToCamelCase) {
            return StrUtil.toUnderlineCase(name);
        }
        return name;
    }

    /**
     * 获取对象id
     *
     * @param model
     * @param entityClass
     * @return
     */
    public static Object getId(Object model, Class<?> entityClass) {
        if (model instanceof SuperEntity) {
            return ((SuperEntity) model).getId();
        } else if (model instanceof SuperRemoteDataEntity) {
            return ((SuperRemoteDataEntity) model).getId();
        } else {
            // 实体没有继承 Entity 和 SuperEntity
            TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
            if (tableInfo == null) {
                return null;
            }
            // 主键类型
            Class<?> keyType = tableInfo.getKeyType();
            if (keyType == null) {
                return null;
            }
            // id 字段名
            String keyProperty = tableInfo.getKeyProperty();

            // 反射得到 主键的值
            Field idField = ReflectUtil.getField(entityClass, keyProperty);
            return ReflectUtil.getFieldValue(model, idField);
        }
    }


}
